package com.qiche.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qiche.aspect.Result;
import com.qiche.constant.AccountType;
import com.qiche.dto.SimpleInsurancePolicyItemDto;
import com.qiche.enums.ResultEnum;
import com.qiche.exception.MySystemException;
import com.qiche.mapper.InsurancePolicyMapper;
import com.qiche.model.InsurancePolicy;
import com.qiche.model.StoreMember;
import com.qiche.model.StoreMemberCar;
import com.qiche.model.User;
import com.qiche.requestpram.PolicyListURL;
import com.qiche.service.InsurancePolicyService;
import com.qiche.service.StoreMemberCarService;
import com.qiche.service.StoreMemberService;
import com.qiche.util.UserUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by Linzw on 2018/01/24.
 */
@Service("policyService")
public class InsurancePolicyServiceImpl extends BaseService<InsurancePolicy> implements InsurancePolicyService {

	@Resource
	private InsurancePolicyMapper policyMapper;

	@Autowired
	private StoreMemberService storeMemberService;
	@Autowired
	private StoreMemberCarService storeMemberCarService;



	@Override
	public PageInfo<InsurancePolicy> selectByPage(InsurancePolicy policy, int page, int limit) {
		Example example = new Example(InsurancePolicy.class);
		Example.Criteria criteria = example.createCriteria();
		//根据当前登录用户加入门店标识

		User currentUser = UserUtils.getCurrentUser();
		if(!UserUtils.checkIsAdmin(currentUser)){
			policy.setMerchantId(currentUser.getMerchantId().longValue());
		}
		if(policy.getStatus()!=null && !"".equals(policy.getStatus().toString())){
			Calendar calendar=Calendar.getInstance();
			calendar.add(Calendar.MONTH,-9);
			Date compareDate=calendar.getTime();

			Calendar calendar2=Calendar.getInstance();
			calendar2.add(Calendar.YEAR,-1);
			Date compareDate2=calendar2.getTime();
			if(policy.getStatus()==1){
				//即将过期
				criteria.andLessThanOrEqualTo("expiryTime",compareDate);
				criteria.andGreaterThanOrEqualTo("expiryTime",compareDate2);
			}else if(policy.getStatus()==0){
				//正常
				criteria.andGreaterThan("expiryTime",compareDate);
			}else if(policy.getStatus()==-1){
				//已过期
				criteria.andLessThan("expiryTime",compareDate2);
			}
		}

		if(policy.getMaxPolicyMoney()!=null && policy.getMinPolicyMoney()!=null){
			criteria.andBetween("policyMoney",policy.getMinPolicyMoney(),policy.getMaxPolicyMoney());
		}
		//条件筛选
		if (policy.getMerchantId() != null && policy.getMerchantId() != 0) {
			criteria.andEqualTo("merchantId", policy.getMerchantId());
		}
		if (StringUtils.isNotBlank(policy.getCode())) {
			criteria.andLike("code", "%" + policy.getCode() + "%");
		}
		if (StringUtils.isNotBlank(policy.getPhone())) {
			criteria.andLike("phone", "%" + policy.getPhone() + "%");
		}
		// 分页查询
		example.setOrderByClause("create_time desc");
		PageHelper.startPage(page, limit);
		List<InsurancePolicy> policyList = selectByExample(example);

		return new PageInfo<>(policyList);
	}

	@Override
	public InsurancePolicy selectById(Long policyId) {
		Example example = new Example(InsurancePolicy.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("id", policyId);
		List<InsurancePolicy> userList = selectByExample(example);
		if (userList.size() > 0) {
			return userList.get(0);
		}
		return null;
	}

	@Override
	public InsurancePolicy selectByCode(String code) {
		Example example = new Example(InsurancePolicy.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("code", code);
		List<InsurancePolicy> userList = selectByExample(example);
		if (userList.size() > 0) {
			return userList.get(0);
		}
		return null;
	}

	@Override
	@Transactional
	public Result savePolicy(InsurancePolicy policy, User user) throws MySystemException {
		// 根据保单号看是否已经存在
		InsurancePolicy temp = selectByCode(policy.getCode());
		if (temp != null) {
			throw new MySystemException(ResultEnum.POLICY_HAS_EXISTED);
		}
		StoreMember storeMember=storeMemberService.selectByKey(policy.getCustomerId());
		StoreMemberCar storeMemberCar=storeMemberCarService.selectByKey(policy.getCustomerCarId());
		// 根据Dto重新封装数据
		policy.setMerchantId(user.getMerchantId().longValue());
		policy.setStatus((byte) 1);
		policy.setCreateTime(new Date());

		policy.setApplicant(storeMember.getName());
		policy.setPhone(storeMember.getPhone());

		policy.setPlateNumber(storeMemberCar.getPlateNumber());
		policy.setFrameNumber(storeMemberCar.getFrameNumber());
		policy.setCarInfo(storeMemberCar.getCarInfo());

		int isOk = policyMapper.insertSelective(policy);
		if (isOk > 0) {
			return Result.createByResultEnum(ResultEnum.SUCCESS);
		} else {
			return Result.createByResultEnum(ResultEnum.FAILURE);
		}
	}

	@Override
	@Transactional
	public Result updatePolicy(InsurancePolicy policy, User user) throws MySystemException {

		InsurancePolicy temp = selectByCode(policy.getCode());
		if (temp != null && policy.getId() != temp.getId()) {
			throw new MySystemException(ResultEnum.POLICY_HAS_EXISTED);
		}
		if(policy.getCustomerId()!=null){
			StoreMember storeMember=storeMemberService.selectByKey(policy.getCustomerId());
			policy.setApplicant(storeMember.getName());
			policy.setPhone(storeMember.getPhone());
		}
		if(policy.getCustomerCarId()!=null){
			StoreMemberCar storeMemberCar=storeMemberCarService.selectByKey(policy.getCustomerCarId());
			policy.setPlateNumber(storeMemberCar.getPlateNumber());
			policy.setFrameNumber(storeMemberCar.getFrameNumber());
			policy.setCarInfo(storeMemberCar.getCarInfo());
		}
		int isOk = policyMapper.updateByPrimaryKeySelective(policy);

		if (isOk > 0) {

			return Result.createByResultEnum(ResultEnum.SUCCESS);
		} else {
			return Result.createByResultEnum(ResultEnum.FAILURE);
		}
	}

	@Override
	public PageInfo<SimpleInsurancePolicyItemDto> selectByPolicyListURL(PolicyListURL policyListURL) {

		PageHelper.startPage(policyListURL.getStartRow(), policyListURL.getPageSize());
		List<SimpleInsurancePolicyItemDto> insurancePolicyItemDtos = policyMapper.selectByPolicyListURL(policyListURL);
		return new PageInfo<>(insurancePolicyItemDtos);
	}

	@Override
	public List<InsurancePolicy> selectPolicyMoneyAll(Integer merchantId) {
		Example example = new Example(InsurancePolicy.class);
		//example.selectProperties("id,policyMoney,createTime");
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("merchantId", merchantId);
		return selectByExample(example);
	}

	@Override
	public List<InsurancePolicy> selectByCustomerId(Long customerId) {
		Example example = new Example(InsurancePolicy.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("customerId", customerId);
		List<InsurancePolicy> userList = selectByExample(example);
		return userList;
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = { Exception.class })
	public Result delInsurancePolicy(Long policyId) {
		int deleteCount=mapper.deleteByPrimaryKey(policyId);
		if(deleteCount==0){
			return Result.createByErrorMessage("删除失败");
		}
		return Result.createBySuccessMessage("删除成功");
	}

	@Override
	public List<InsurancePolicy> selectByMerchantId() {
		User currentUser = (User) SecurityUtils.getSubject().getPrincipal();
		Example example = new Example(InsurancePolicy.class);
		Example.Criteria criteria = example.createCriteria();
		if (currentUser.getAccountType() != AccountType.ADMIN) {
			criteria.andEqualTo("merchantId", currentUser.getMerchantId());
		}

		List<InsurancePolicy> policyList = selectByExample(example);
		return policyList;
	}

}
